package cn.kgc.shiro02.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/6/2
 * @Description:
 */
public class CustomerRealm extends AuthorizingRealm {

    //  授权  认证通过之后 用户访问受限资源时   该方法会被自动调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("=============授权的方法被调用=================");
        // 获取用户的身份信息   username
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();

        //  TODO 查询数据库   username     RBAC
        //  select *  from user  wher  username = ?  uid  -> u-r  ->  rid  -> role

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //simpleAuthorizationInfo.addRole("super");
        //simpleAuthorizationInfo.addRole("admin");

        List<String> roles = Arrays.asList("admin", "super");
        simpleAuthorizationInfo.addRoles(roles);

        // 添加用户拥有的权限字符串
        //simpleAuthorizationInfo.addStringPermission("user:add");
        //simpleAuthorizationInfo.addStringPermission("user:update");
        simpleAuthorizationInfo.addStringPermission("user:*");


        return simpleAuthorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken  usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        // TODO 根据用户名查询数据库  username   User user ==  null   select *  from user  where username = ?  password = e10adc3949ba59abbe56e057f20f883e
        if("tom".equals(username)){
            //return   new SimpleAuthenticationInfo("tom","e10adc3949ba59abbe56e057f20f883e",this.getName());
           //return  new SimpleAuthenticationInfo("tom","370e78d7d264afcf8422f3752d407792", ByteSource.Util.bytes("helloshiro"),this.getName());
           return  new SimpleAuthenticationInfo("tom","4f35e5c7ceb7a9d49073dc7f0ee72b22", ByteSource.Util.bytes("helloshiro"),this.getName());
        }

        return null;
    }
}
